<?php

namespace common;

class Tree
{
    /**
     * 树形显示数组数据,必须包含pid参数
     * @author lijia
     * @date 2019-08-08
     */
    static public function menu($cate, $lefthtml = '|— ', $pid = 0, $lvl = 0, $leftpin = 0)
    {
        $arr = array();
        foreach ($cate as $v) {
            if ($v['pid'] == $pid) {
                $v['lvl'] = $lvl + 1;
                $v['leftpin'] = $leftpin + 0;
                $v['lefthtml'] = str_repeat($lefthtml, $lvl);
                $v['ltitle'] = $v['lefthtml'] . $v['title'];
                $arr[] = $v;
                $arr = array_merge($arr, self::menu($cate, $lefthtml, $v['id'], $lvl + 1, $leftpin + 20));
            }
        }
        return $arr;
    }

    /**
     * 树形显示数组数据,必须包含pid参数
     * @date 2019-08-08
     */
    static public function cate($cate, $lefthtml = '|— ', $pid = 0, $lvl = 0, $leftpin = 0)
    {
        $arr = array();
        foreach ($cate as $v) {
            if ($v['pid'] == $pid) {
                $v['lvl'] = $lvl + 1;
                $v['leftpin'] = $leftpin + 0;
                $v['lefthtml'] = str_repeat($lefthtml, $lvl);
                $arr[] = $v;
                $arr = array_merge($arr, self::cate($cate, $lefthtml, $v['category_id'], $lvl + 1, $leftpin + 20));
            }
        }
        return $arr;
    }

    /**
     * 获取包括自己的所有子分类
     * @param $cate
     * @param $pid
     * @return string
     */
    static public function getAllCid($cate, $pid)
    {
        $str = '';
        foreach ($cate as $v) {
            if ($v['pid'] == $pid) {
                $str .= ','.$v['category_id'];
            }
        }
        return $pid.$str;
    }

    /**
     * 检测是否选择权限
     * @author lijia
     * @date 2019-08-08
     */
    static public function auth($cate, $pid = 0, $rules)
    {
        $arr = array();
        $rulesArr = explode(',', $rules);
        foreach ($cate as $v) {
            if ($v['pid'] == $pid) {
                if (in_array($v['id'], $rulesArr)) {
                    $v['checked'] = true;
                }
                $v['open'] = true;
                $arr[] = $v;
                $arr = array_merge($arr, self::auth($cate, $v['id'], $rules));
            }
        }
        return $arr;
    }

    /**
     * 组装存在上下级关系的数组
     * @author lijia
     * @date 2019-08-08
     */
    public function getTree($data, $pId, $ruleArr)
    {
        $tree = [];
        foreach ($data as $k => $v) {
            if (in_array($v['id'], $ruleArr)) {
                $v['checkArr'] = ['type' => 0, 'isChecked' => 1];
            } else {
                $v['checkArr'] = ['type' => 0, 'isChecked' => 0];
            }
            if ($v['pid'] == $pId) {
                $v['children'] = self::getTree($data, $v['id'], $ruleArr);
                $tree[] = $v;
            }
        }
        return $tree;
    }

}
